<template>
  <section>
    <el-col v-show="pwdVisible">
      <el-form label-width="6rem" ref="newForm" class="pwdForm">
        <el-form-item label="请输入密码">
          <el-input
            v-model="initializePwd"
            type="password"
            placeholder="请输入初始化密码"
            style="width:15rem"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item>
        
        </el-form-item>-->
      </el-form>
      <h2 class="pwdTitle">注：初始化房间信息前，请先备份数据库，以免想恢复到以前状态时数据丢失</h2>
      <el-button type="primary" class="pwdButton" @click.native="confirmPwd">确认</el-button>
    </el-col>
    <el-form
      label-width="8rem"
      ref="initializeForm"
      class="initializeForm"
      v-show="formVisible"
      :model="initializeData"
      :loading="initializeLoading"
      :rules="rules"
    >
      <el-form-item label="所属区域" prop="area">
        <el-select v-model="initializeData.area" placeholder="区域编号" @change="areaChange">
          <el-option v-for="item in area" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="宿舍楼编号" prop="dorm">
        <el-select
          v-model="initializeData.dorm"
          placeholder="宿舍楼编号"
          @change="dormChange(initializeData.dorm)"
        >
          <el-option v-for="item in dorm" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="10">
          <el-form-item label="初始化楼层" required>
            <el-col :span="11">
              <el-form-item prop="beginLayers">
                <el-select v-model="initializeData.beginLayers" placeholder="楼层">
                  <el-option
                    v-for="item in layers"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="1" :offset="1">-</el-col>
            <el-col :span="11">
              <el-form-item prop="endLayers">
                <el-select v-model="initializeData.endLayers" placeholder="楼层">
                  <el-option
                    v-for="item in layers"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 重复行 -->
      <el-row>
        <el-col :span="4">
          <el-form-item
            v-for="(goods, index) in initializeData.goods"
            label="物品名称"
            :key="goods.key"
            :prop="'goods.' + index + '.name'"
            :rules="{required: true, message: '不能为空', trigger: 'blur'}"
          >
            <el-input v-model="goods.name" style="width:8rem"></el-input>
            <!-- <el-button @click.prevent="removeGoods(goods)" size="small">删除</el-button> -->
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            v-for="(goods, index) in initializeData.goods"
            label="物品编码"
            :key="goods.key"
            :prop="'goods.' + index + '.number'"
            :rules="{ required: true, message: '不能为空', trigger: 'blur'}"
          >
            <el-input
              v-model="goods.number"
              style="width:8rem"
              @blur="checkGoodsName(goods.number,index)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            v-for="(goods, index) in initializeData.goods"
            label="物品数量"
            :key="goods.key"
            :prop="'goods.' + index + '.count'"
            :rules="[{required: true, message: '不能为空', trigger: 'blur'},{ type: 'number', message: '值必须为数字值'}]"
          >
            <el-input v-model.number="goods.count" style="width:7rem"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            v-for="(goods, index) in initializeData.goods"
            label="物品单价"
            :key="goods.key"
            :prop="'goods.' + index + '.price'"
            :rules="[{required: true, message: '不能为空', trigger: 'blur'},{ type: 'number', message: '值必须为数字值'}]"
          >
            <el-input v-model.number="goods.price" style="width:7rem"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            v-for="(goods, index) in initializeData.goods"
            label="赔偿价格"
            :key="goods.key"
            :prop="'goods.' + index + '.reparation'"
            :rules="[{required: true, message: '不能为空', trigger: 'blur'},{ type: 'number', message: '值必须为数字值'}]"
          >
            <el-input v-model.number="goods.reparation" style="width:7rem"></el-input>&nbsp;&nbsp;&nbsp;&nbsp;
            <el-button @click.prevent="removeGoods(goods)" size="small" type="danger">删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="submitForm('initializeForm')">提交</el-button>
        <el-button @click="addGoods" type="success">新增资产</el-button>
        <el-button @click="resetForm('initializeForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>
<script>
import { getArea } from "../../api/area.js";
import { getDorm, getFloor } from "../../api/dorm.js";
import {
  checkNumberRepeat,
  roomGoodsInitialize,
  roomGoodsInitializeConfirmPwd
} from "../../api/goods.js";
export default {
  data() {
    return {
      pwdVisible: true,
      initializePwd: "",
      formVisible: false,
      initializeLoading: false,
      initializeData: {
        area: "",
        dorm: "",
        beginLayers: "",
        endLayers: "",
        goods: []
      },
      rules: {
        area: [{ required: true, message: "请选择区域", trigger: "change" }],
        dorm: [{ required: true, message: "请选择宿舍楼", trigger: "change" }],
        beginLayers: [
          { required: true, message: "请选择起始楼层", trigger: "change" }
        ],
        endLayers: [
          { required: true, message: "请选择结束楼层", trigger: "change" }
        ],
        number: [{ required: true, message: "请选择结束楼层", trigger: "blur" }]
      },
      area: [
        {
          value: "",
          label: ""
        }
      ],
      dorm: [
        {
          value: "",
          label: ""
        }
      ],
      layers: []
    };
  },
  methods: {
    confirmPwd() {
      // 进行密码验证
      roomGoodsInitializeConfirmPwd(this.initializePwd).then(res => {
        if (res) {
          this.pwdVisible = false;
          this.formVisible = true;
        }
      });
    },
    getArea() {
      getArea().then(res => {
        if (res) {
          this.area = res.msg;
        }
      });
    },
    areaChange() {
      if (this.initializeData.area === "") {
        return true;
      }
      getDorm(this.initializeData.area).then(res => {
        if (res) {
          this.initializeData.dorm = null;
          this.dorm = res.msg;
        } else {
          this.dorm = [
            {
              value: "",
              label: ""
            }
          ];
          this.initializeData.dorm = "";
        }
      });
    },
    dormChange(dorm) {
      if (dorm === "") {
        return true;
      }
      // 获取当前楼层
      getFloor(this.initializeData.area, this.initializeData.dorm).then(res => {
        if (res) {
          this.layers = [];
          let floor = res.msg[0].d_layers;
          for (let i = 1; i <= floor; i++) {
            let _floor = { value: i, label: i };
            this.layers.push(_floor);
          }
        }
      });
    },
    removeGoods(item) {
      var index = this.initializeData.goods.indexOf(item);
      if (index !== -1) {
        this.initializeData.goods.splice(index, 1);
      }
    },
    addGoods() {
      this.initializeData.goods.push({
        name: "",
        number: "",
        price: "",
        reparation: "",
        count: "",
        key: Date.now()
      });
    },
    // 防止物品编号重复
    checkGoodsName(goodsNumber, index) {
      // 先检验是否与重复行中的相同
      this.initializeLoading = true;
      for (let i = 0; i < this.initializeData.goods.length; i++) {
        if (this.initializeData.goods[i].number === goodsNumber) {
          if (i !== index) {
            this.initializeLoading = false;
            this.$message.error("编码重复!");
            this.initializeData.goods[index].number = "";
            return false;
          }
        }
      }
      // 与已存在的编码进行验证
      checkNumberRepeat(goodsNumber, "room").then(res => {
        if (!res) {
          this.initializeLoading = false;
          this.$message.error("编码重复!");
          this.initializeData.goods[index].number = "";
          return false;
        } else {
          this.initializeLoading = false;
          return true;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submitForm(formName) {
      this.initializeLoading = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 进行初始化
          roomGoodsInitialize(this.initializeData).then(res => {
            this.initializeLoading = false;
            if (res) {
              this.$refs[formName].resetFields();
              this.$message.success(res.msg);
            }
          });
        } else {
          this.initializeLoading = false;
          // console.log("error submit!!");
          return false;
        }
      });
    }
  },
  mounted() {
    this.getArea();
  }
};
</script>
<style>
.pwdForm {
  /* 实现元素居中 */
  position: absolute;
  top: 20%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* align-self: center  此属性目前暂未支持，书上看来的，一键垂直居中*/
}
.pwdTitle {
  position: absolute;
  top: 30%; /* 上浮一点 */
  left: 50%;
  transform: translate(-50%, -50%);
  color: rgb(243, 51, 51);
  font-size: 1.5rem;
}
.pwdButton {
  position: absolute;
  top: 50%; /* 上浮一点 */
  left: 50%;
  transform: translate(-50%, -50%);
  width: 10rem;
}
.initializeForm {
  width: 80%;
  /* height: 55em; */
  padding: 1.5em 1.5em;
  border: 1px solid rgb(178, 194, 184);
  border-radius: 2%;
  /* position: absolute; */
  /* 上浮一点 */
  /* top: 50%; */
  /* left: 50%; */
  /* transform: translate(-50%, -50%); */
  margin: auto;
}
</style>
